package org.finesys.common.excel.converter;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;

/**
 * 时间 转换器
 */
public enum LocalTimeStringConverter implements Converter<LocalTime> {
    /**
     * 实例
     */
    INSTANCE;


    public static final String DATE_FORMAT_21 = "yyyyMMdd HH:mm:ss.SSS";
    public static final String DATE_FORMAT_17 = "yyyyMMddHHmmssSSS";
    public static final String DATE_FORMAT_23 = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String DATE_FORMAT_23_FORWARD_SLASH = "yyyy/MM/dd HH:mm:ss.SSS";

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return LocalTime.parse(cellData.getStringValue());
        } else {
            String pattern = contentProperty.getDateTimeFormatProperty().getFormat();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
            return LocalTime.parse(cellData.getStringValue(), dateTimeFormatter);
        }
    }


    @Override
    public WriteCellData<?> convertToExcelData(LocalTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        DateTimeFormatter dateTimeFormatter;
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_TIME;
        } else {
            String pattern = contentProperty.getDateTimeFormatProperty().getFormat();
            dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        }
        return new WriteCellData<>(value.format(dateTimeFormatter));
    }
}